package com.leo.view;

import com.leo.EmailFxApp;
import com.leo.bean.EmailInfo;
import com.leo.common.MailApiUtil;
import com.leo.common.MailViewUtils;
import com.leo.db.DaoMapperProxy;
import com.leo.mapper.UserMapper;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Duration;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Date;

/**
 * @author wangss
 * @date 2023/02/21 19:15
 * @description
 **/
public class AddMailVIew {

    public AddMailVIew(int userId, StackPane emailContentPane, StackPane addEmailBtn, TreeItem root) {
        // 布局GridPane
        GridPane gridPane = new GridPane();
        // 居中、组件水平距离和垂直距离
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        // 内边距
        gridPane.setPadding(new Insets(25, 25, 25, 25));

        // 给列设置样式
        ColumnConstraints columnConstraints = new ColumnConstraints();
        columnConstraints.setFillWidth(true);
        columnConstraints.setHgrow(Priority.NEVER);
        columnConstraints.setMaxWidth(150);
        for (int i = 0; i < 2; i++) {
            gridPane.getColumnConstraints().add(columnConstraints);
        }

        // 给每行设置样式
        RowConstraints rowConstraints = new RowConstraints();
        rowConstraints.setFillHeight(true);
        rowConstraints.setVgrow(Priority.NEVER);
        for (int i = 0; i < 5; i++) {
            gridPane.getRowConstraints().add(rowConstraints);
        }

        RowConstraints rowConstraints6 = new RowConstraints();
        rowConstraints6.setFillHeight(true);
        rowConstraints6.setVgrow(Priority.NEVER);
        rowConstraints6.setMinHeight(30);
        rowConstraints6.setMaxHeight(30);
        gridPane.getRowConstraints().add(rowConstraints6);

        // 邮箱设置
        Text welcome = new Text("邮箱设置");
        welcome.setId("welcome-text");
        // add(Node var1, int var2, int var3, int var4, int var5), var2 第几列，var3 第几行，var4 占用几列，var5 占用几行
        gridPane.add(welcome, 0, 0, 2, 1);

        // 邮箱类型
        Label emailTypeLabel = new Label("邮箱类型");
        gridPane.add(emailTypeLabel, 0, 1);
        ChoiceBox<String> choiceEmailTypeBox = new ChoiceBox<>();
        choiceEmailTypeBox.getItems().addAll("pop3", "imap");
        choiceEmailTypeBox.setValue("pop3");
        gridPane.add(choiceEmailTypeBox, 1, 1);

        // 邮箱
        Label emailLabel = new Label("邮箱账号");
        gridPane.add(emailLabel, 0, 2);
        TextField emailField = new TextField();
        emailField.setPromptText("邮箱");
        gridPane.add(emailField, 1, 2);
        emailLabel.setLabelFor(emailField);

        // 密码
        Label emailPasswordLabel = new Label("邮箱密码");
        gridPane.add(emailPasswordLabel, 0, 3);
        PasswordField emailPasswordField = new PasswordField();
        emailPasswordField.setPromptText("密码");
        gridPane.add(emailPasswordField, 1, 3);
        emailPasswordLabel.setMnemonicParsing(true);
        emailPasswordLabel.setLabelFor(emailPasswordField);

        // 发信名称
        Label emailNameLabel = new Label("发信名称");
        gridPane.add(emailNameLabel, 0, 4);
        TextField emailNameField = new TextField();
        emailNameField.setPromptText("发信名称");
        gridPane.add(emailNameField, 1, 4);
        emailNameLabel.setLabelFor(emailNameField);

        // 接收服务器
        Label mailServerLabel = new Label(choiceEmailTypeBox.getValue() + "服务器");
        gridPane.add(mailServerLabel, 0, 5);
        TextField mailServerField = new TextField();
        gridPane.add(mailServerField, 1, 5);
        mailServerLabel.setLabelFor(mailServerField);

        // 接收服务器端口
        Label mailServerPortLabel = new Label("SSL 端口");
        gridPane.add(mailServerPortLabel, 2, 5);
        TextField mailServerPortField = new TextField("110");
        gridPane.add(mailServerPortField, 3, 5);
        mailServerPortLabel.setLabelFor(mailServerPortField);

        // 发送服务器
        Label mailSendServerLabel = new Label("SMTP服务器");
        gridPane.add(mailSendServerLabel, 0, 6);
        TextField mailSendServerField = new TextField();
        gridPane.add(mailSendServerField, 1, 6);
        mailSendServerLabel.setLabelFor(mailSendServerField);

        // 发送服务器端口
        Label mailSendServerPortLabel = new Label("SSL 端口");
        gridPane.add(mailSendServerPortLabel, 2, 6);
        TextField mailSendServerPortField = new TextField("25");
        gridPane.add(mailSendServerPortField, 3, 6);
        mailSendServerPortLabel.setLabelFor(mailSendServerPortField);

        // 登录按钮
        HBox hBox = new HBox();
        Button login = new Button("新建");
        Button cancel = new Button("取消");
        hBox.getChildren().addAll(login, cancel);
        hBox.setAlignment(Pos.CENTER);
        hBox.setSpacing(15);
        gridPane.add(hBox, 0, 7, 4, 1);

        // 登录成功或者错误提示
        HBox messageHbox = new HBox();
        Label message = new Label();
        message.setWrapText(true);
        message.getStyleClass().add("message");

        messageHbox.getChildren().add(message);
        messageHbox.setAlignment(Pos.CENTER);
        gridPane.add(messageHbox, 0, 8, 4, 1);

        // 邮箱类型变动的时候改变端口
        choiceEmailTypeBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            mailServerLabel.setText(newValue + "服务器");
            if ("pop3".equals(newValue)) {
                mailServerPortField.setText("110");
                mailSendServerPortField.setText("25");
            } else if ("imap".equals(newValue)) {
                mailServerPortField.setText("993");
                mailSendServerPortField.setText("465");
            }
            message.setText("");
        });

        Scene scene = new Scene(gridPane, 600, 400);
        Stage stage = new Stage();

        login.setOnAction(actionEvent -> {
            // 邮箱类型
            String mailType = choiceEmailTypeBox.getValue();
            // 邮箱
            String mail = emailField.getText();
            // 密码
            String mailPassword = emailPasswordField.getText();
            // 发信名称
            String mailName = emailNameField.getText();
            // 接收服务器
            String revServer = mailServerField.getText();
            // 接收端口
            String revServerPort = mailServerPortField.getText();
            // 发送服务器
            String sendServer = mailSendServerField.getText();
            // 发送端口
            String sendServerPort = mailSendServerPortField.getText();

            if (StringUtils.isAnyBlank(mailType, mail, mailPassword, mailName, revServer, revServerPort, sendServer, sendServerPort)) {
                message.setText("请填写全部内容");
                return;
            }

            EmailInfo mailInfo = new EmailInfo();
            mailInfo.setType(mailType);
            mailInfo.setEmail(mail);
            mailInfo.setPassword(mailPassword);
            mailInfo.setShowName(mailName);
            mailInfo.setSendName(mailName);
            mailInfo.setReceiveServer(revServer);
            mailInfo.setReceivePort(Integer.parseInt(revServerPort));
            mailInfo.setSendServer(sendServer);
            mailInfo.setSendPort(Integer.parseInt(sendServerPort));
            mailInfo.setIntervalTime(5);
            mailInfo.setStatus(0);
            mailInfo.setCreateTime(new Date());
            mailInfo.setUpdateTime(new Date());
            mailInfo.setEmail_user_id(userId);

            // 如果没有测试则先测试
            boolean checkConnect = MailApiUtil.checkConnect(mailInfo);
            if (!checkConnect) {
                message.setText("邮箱不可用，请核对填写信息");
                return;
            }

            try {
                // 入库
                UserMapper userMapper = DaoMapperProxy.getProxyInstance(UserMapper.class);
                int num = userMapper.insertMailInfo(mailInfo);
                if (num == 1) {
                    // 移除邮箱页面的新增按钮
                    emailContentPane.getChildren().remove(addEmailBtn);
                    message.setText("新增成功");

                    MailViewUtils.addMailUserList(Arrays.asList(mailInfo), root, emailContentPane);

                    KeyFrame key = new KeyFrame(Duration.millis(3000), new KeyValue(scene.getRoot().opacityProperty(), 0));
                    Timeline timeline = new Timeline(key);
                    timeline.setOnFinished(e -> stage.close());
                    timeline.play();
                }
            } catch (Exception e) {
                message.setText("新增邮箱出错");
                return;
            }
        });

        cancel.setOnAction(event -> {
            stage.close();
        });

        message.textProperty().addListener((observableValue, s, t1) -> {
            if (t1.length() > 15 && null != message.getTooltip()) {
                message.getTooltip().setText(t1);
            } else if (t1.length() > 15 && null == message.getTooltip()) {
                Tooltip tooltip = new Tooltip(t1);
                message.setTooltip(tooltip);
            } else {
                message.setTooltip(null);
            }
        });

        stage.setScene(scene);
        stage.setTitle("邮箱设置");
        // 加载css样式
        scene.getStylesheets().add(EmailFxApp.class.getResource("css/addemail.css").toExternalForm());
        stage.setResizable(false);
        stage.sizeToScene();
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.showAndWait();
    }
}
